const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库配置
const dbConfig = {
    host: process.env.DB_HOST || "43.143.253.188",
    port: parseInt(process.env.DB_PORT || "3306", 10),
    user: process.env.DB_USER || "nextjs",
    password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
    database: process.env.DB_NAME || "nextjs",
    charset: 'utf8mb4',
    timezone: '+08:00',
    multipleStatements: true,
    dateStrings: true,
    supportBigNumbers: true,
    bigNumberStrings: true,
    typeCast: true,
    acquireTimeout: 60000,
    timeout: 60000,
};

// 坐骑基础数据
const mountBaseData = {
    "1": {
        "ap": 2750,
        "apIni": 50,
        "descr": "一匹不羁的野马，变成了战马。",
        "hp": -1000,
        "hpIni": -1000,
        "img": "zhanma",
        "mp": -1000,
        "mpIni": -1000,
        "name": "战马",
        "sp": 50,
        "spIni": -50,
        "type": 1
    },
    "2": {
        "ap": 3500,
        "apIni": 100,
        "descr": "刘备的坐骑，马作的卢飞快，弓如霹雳弦惊。",
        "hp": 13550,
        "hpIni": 50,
        "img": "dilu",
        "mp": -1000,
        "mpIni": -1000,
        "name": "的卢",
        "sp": -1000,
        "spIni": -1000,
        "type": 2
    },
    "3": {
        "ap": -1000,
        "apIni": -1000,
        "descr": "曹操之爱马，\"绝影\"之名就是因为其速度飞快而得，意为速度快的连自己的影子都跟不上。",
        "hp": 13550,
        "hpIni": 50,
        "img": "jueying",
        "mp": 13550,
        "mpIni": 50,
        "name": "绝影",
        "sp": -1000,
        "spIni": -1000,
        "type": 2
    },
    "4": {
        "ap": 3500,
        "apIni": 100,
        "descr": "本名\"赤菟\"，其实是个红色的大兔子。",
        "hp": -1000,
        "hpIni": -1000,
        "img": "chitu",
        "mp": -1000,
        "mpIni": -1000,
        "name": "赤兔",
        "sp": 100,
        "spIni": 0,
        "type": 2
    },
    "5": {
        "ap": -1000,
        "apIni": -1000,
        "descr": "孙权的坐骑，耐力惊人，速度飞快，奔跑如行云流水，譬如白矾顺流。",
        "hp": 13550,
        "hpIni": 50,
        "img": "jingfan",
        "mp": -1000,
        "mpIni": -1000,
        "name": "惊帆",
        "sp": 100,
        "spIni": 0,
        "type": 2
    },
    "6": {
        "ap": -1000,
        "apIni": -1000,
        "descr": "曹操之爱马，爪黄飞电通体雪白，四个黄蹄子，气质高贵非凡，傲气不可一世。",
        "hp": 17100,
        "hpIni": 100,
        "img": "feidian",
        "mp": -1000,
        "mpIni": -1000,
        "name": "爪黄飞电",
        "sp": -1000,
        "spIni": -1000,
        "type": 3
    },
    "7": {
        "ap": -1000,
        "apIni": -1000,
        "descr": "久经战场，全身发黑的老马。",
        "hp": -1000,
        "hpIni": -1000,
        "img": "laoheima",
        "mp": 17100,
        "mpIni": 100,
        "name": "老黑马",
        "sp": -1000,
        "spIni": -1000,
        "type": 3
    },
    "8": {
        "ap": 5000,
        "apIni": 200,
        "descr": "为黄忠之马，是一匹汗血马，气势非凡，性情暴躁，极具攻击性，牙齿异常锋利，力量与速度都在同类中屈指可数。",
        "hp": -1000,
        "hpIni": -1000,
        "img": "liaoyuanhuo",
        "mp": -1000,
        "mpIni": -1000,
        "name": "燎原火",
        "sp": -1000,
        "spIni": -1000,
        "type": 3
    },
    "9": {
        "ap": -1000,
        "apIni": -1000,
        "descr": "通体如火焰般赤红的名马，俗称赤兔马，可日行千里，有\"人中吕布，马中赤兔\"之称，曾为吕布坐骑，后为关羽所得。",
        "hp": -1000,
        "hpIni": -1000,
        "img": "chitu",
        "mp": -1000,
        "mpIni": -1000,
        "name": "赤兔胭脂兽",
        "sp": 150,
        "spIni": 50,
        "type": 3
    }
};

async function importMountBaseData() {
    let connection;

    try {
        console.log('🚀 开始连接远程数据库...');
        console.log(`📡 连接地址: ${dbConfig.host}:${dbConfig.port}`);
        console.log(`🗄️ 数据库: ${dbConfig.database}`);

        // 连接数据库
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功！');

        // 检查表是否存在
        console.log('🔍 检查 mount_base 表是否存在...');
        const [tables] = await connection.execute(
            "SHOW TABLES LIKE 'mount_base'"
        );

        if (tables.length === 0) {
            console.log('❌ mount_base 表不存在，请先创建表结构');
            return;
        }

        console.log('✅ mount_base 表存在');

        // 清空现有数据（可选）
        console.log('🗑️ 清空现有坐骑基础数据...');
        await connection.execute('DELETE FROM mount_base');
        console.log('✅ 现有数据已清空');

        // 插入新数据
        console.log('📥 开始导入坐骑基础数据...');

        const insertSql = `
      INSERT INTO mount_base (
        id, name, descr, img, ap, apIni, hp, hpIni, mp, mpIni, sp, spIni, type, price, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NULL)
    `;

        let successCount = 0;
        let errorCount = 0;

        for (const [id, data] of Object.entries(mountBaseData)) {
            try {
                const values = [
                    parseInt(id),
                    data.name,
                    data.descr,
                    data.img,
                    data.ap,
                    data.apIni,
                    data.hp,
                    data.hpIni,
                    data.mp,
                    data.mpIni,
                    data.sp,
                    data.spIni,
                    data.type,
                    1980, // 默认价格
                ];

                await connection.execute(insertSql, values);
                console.log(`✅ 导入坐骑: ${data.name} (ID: ${id})`);
                successCount++;

            } catch (error) {
                console.error(`❌ 导入坐骑失败: ${data.name} (ID: ${id})`, error.message);
                errorCount++;
            }
        }

        console.log('\n📊 导入结果统计:');
        console.log(`✅ 成功导入: ${successCount} 条记录`);
        console.log(`❌ 导入失败: ${errorCount} 条记录`);
        console.log(`📈 总计处理: ${Object.keys(mountBaseData).length} 条记录`);

        // 验证导入结果
        console.log('\n🔍 验证导入结果...');
        const [results] = await connection.execute('SELECT COUNT(*) as count FROM mount_base');
        console.log(`📊 数据库中现有坐骑数量: ${results[0].count}`);

        // 显示导入的坐骑列表
        const [mounts] = await connection.execute(`
      SELECT id, name, type, ap, hp, mp, sp 
      FROM mount_base 
      ORDER BY id ASC
    `);

        console.log('\n📋 导入的坐骑列表:');
        mounts.forEach(mount => {
            const typeNames = { 1: '战马', 2: '名马', 3: '神马' };
            console.log(`  ${mount.id}. ${mount.name} (${typeNames[mount.type] || '未知'}) - AP:${mount.ap}, HP:${mount.hp}, MP:${mount.mp}, SP:${mount.sp}`);
        });

        console.log('\n🎉 坐骑基础数据导入完成！');

    } catch (error) {
        console.error('❌ 导入过程中发生错误:', error);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 执行导入
if (require.main === module) {
    importMountBaseData()
        .then(() => {
            console.log('✅ 脚本执行完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('❌ 脚本执行失败:', error);
            process.exit(1);
        });
}

module.exports = { importMountBaseData, mountBaseData };
